package com.napenalki.toto.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.napenalki.toto.dao.SpecialEventDao;
import com.napenalki.toto.domain.SpecialEvent;
import com.napenalki.toto.domain.SpecialEvents;

@Transactional
@Repository
public class JpaSpecialEventDao implements SpecialEventDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public SpecialEvent addSpecialEvent(SpecialEvent event) {
        entityManager.persist(event);
        return event;
    }

    @Override
    public SpecialEvent findSpecialEventById(int id) {
        return entityManager.find(SpecialEvent.class, id);
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<SpecialEvent> findAllSpecialEvents() {
        return entityManager
            .createQuery("SELECT event FROM SpecialEvent event")
            .getResultList();
    }

    @Override
    public SpecialEvent findSpecialEventByType(SpecialEvents eventType) {
        Query query = entityManager
            .createQuery("SELECT event FROM SpecialEvent event WHERE event.eventType = :eventType");
        query.setParameter("eventType", eventType);
        try {
            return (SpecialEvent) query.getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public List<SpecialEvent> findAllFinishedSpecialEvents() {
        Query query = entityManager
            .createQuery("SELECT event FROM SpecialEvent event WHERE event.result IS NOT NULL");
        return query.getResultList();
    }

    @Override
    public SpecialEvent updateSpecialEvent(SpecialEvent event) {
        SpecialEvent eventx = findSpecialEventByType(event.getEventType());
        
        if (eventx == null) {
            entityManager.persist(event);
            return event;
        } else {
            eventx.setDate(event.getDate());
            eventx.setLocked(event.isLocked());
            eventx.setResult(event.getResult());
            eventx.setEventType(event.getEventType());
            entityManager.merge(eventx);
            return eventx;
        }
    }

    @Override
    public void deleteSpecialEvent(SpecialEvent event) {
        SpecialEvent eventx = findSpecialEventById(event.getId());
        if (eventx != null) {
            entityManager.remove(eventx);
        }
    }
}
